Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example

Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6

Return: 1 --> 2 --> 3 --> 4 --> 5

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode removeElements(ListNode head, int val) {
  11. if (head == null)
  12. return null;
  13. ListNode f = new ListNode(0);
  14. ListNode p = f;
  15. while (head != null) {
  16. if (head.val != val) {
  17. p.next = head;
  18. p = p.next;
  19. }
  20. head = head.next;
  21. }
  22. p.next = null;
  23. return f.next;
  24. }
  25. }